import { ZBreadcrumbItem } from "@/layout/ZBreadcrumb.vue";
import { routes } from "@/router/routes";
import { getMenusFromRoutes, ZMenuItem } from "@/router/routes/helpers";
import { zError } from "@/utils/console";
import { defineStore } from "pinia";
import { ref } from "vue";

export const MENU_STORE = "menu";

export const useMenuStore = defineStore(MENU_STORE, () => {
  function getMenus() {
    return getMenusFromRoutes(routes);
  }

  const activeMenu = ref("");
  function setActiveMenu(menuKey: string) {
    activeMenu.value = menuKey;
  }

  function getBreadcrumbByPath(path = "/") {
    const crumbs: ZBreadcrumbItem[] = [];
    function recursive(menus: ZMenuItem[]) {
      for (const menu of menus) {
        const { key } = menu;
        if (path.startsWith(key)) {
          crumbs.push({
            title: menu.label,
            icon: menu.icon,
            path: menu.key,
            children: menu.children,
          });
          if (path === menu.key) {
            return;
          } else if (menu.children?.length) {
            recursive(menu.children);
          } else {
            zError("incorrect path received");
          }
        }
      }
    }

    recursive(getMenus());
    return crumbs;
  }

  return {
    getMenus,
    activeMenu,
    setActiveMenu,
    getBreadcrumbByPath,
  };
});
